package com.uton.rfidcontroller.common.net.base;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.uton.rfidcontroller.R;
import com.uton.rfidcontroller.common.utils.LogUtil;
import com.uton.rfidcontroller.common.utils.Utils;
import com.uton.rfidcontroller.model.base.BaseModel;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by 王家宝 on 2017/8/30.
 * Email:639586819@qq.com
 * Tel:18241150668
 */
public abstract class BaseObserver<T> implements Observer<BaseModel<T>> {

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(BaseModel<T> value) {
        LogUtil.d(Utils.getString(R.string.log_request_begin));
        if (value.isIsSuccess()) {
            if (value.isIsEmpty()) {
                T t = value.getData();
                onHandleSuccess(t);
            } else {
                T t = value.getData();
                Gson g = new GsonBuilder().serializeNulls().create();
                LogUtil.d("内容是：" + g.toJson(t));
                onHandleSuccess(t);
            }

        } else {
            String errorMsg = value.getTreatmentResult().getMessage() != null ?
                    value.getTreatmentResult().getMessage() :
                    Utils.getString(R.string.toast_network_error);
            Utils.showShortToast(errorMsg);
            onHandleError();
        }
    }

    @Override
    public void onError(Throwable e) {
        Utils.showShortToast(Utils.getString(R.string.toast_request_error) + e.getMessage());
        LogUtil.d("错误原因" + e.getMessage());
        onHandleError();
    }

    @Override
    public void onComplete() {
        LogUtil.d(Utils.getString(R.string.log_request_complete));
        onHandleComplete();
    }

    protected abstract void onHandleSuccess(T t);

    protected abstract void onHandleError();

    protected abstract void onHandleComplete();

}
